package com.wendy.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendy.model.User;
import com.wendy.service.UserService;
import com.wendy.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author zhuwending
 */
@Component
public class UserAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.selectUserForLogin(username, password);
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = StringUtils.isNotEmpty(header) && "XMLHttpRequest".equalsIgnoreCase(header);
        if (isAjax) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.successResponse("登录成功")));
        } else {
            super.setDefaultTargetUrl("/page/index");
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
